import java.io.*;
import java.net.*;
import java.util.*;

public class NS9_userA {
    
    public static int find_pow(int a, int b,int c) {
        int i,final_ans=1;
        for(i=0;i<b;i++)
            final_ans=(final_ans*(a%c))%c;
        return final_ans%c;
    }
    public static void main(String[] args) throws IOException {
        Scanner sc = new Scanner(System.in);

        System.out.println("Enter value of P");
        int P = sc.nextInt();
        
        System.out.println("Enter value of a");
        int a = sc.nextInt();

        System.out.println("Enter value of Xa");
        int Xa = sc.nextInt();

        int Ya;
        Ya=find_pow(a,Xa,P);
        
        ServerSocket ss = null;
        Socket s = null;
        ss = new ServerSocket(7777);
        s = ss.accept();
        DataOutputStream dos = new DataOutputStream(s.getOutputStream());
        DataInputStream dis = new DataInputStream(s.getInputStream());

        dos.writeUTF(Integer.toString(Ya));
        String Yb = dis.readUTF();
            
        int k;
        k=find_pow(Integer.parseInt(Yb),Xa,P);
            
        System.out.println("Key is "+k);
        
    }
}
